import axios, { AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';

import { ErrorCode } from './index'; 


const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
});

service.interceptors.request.use(
  (config) => {
    if (localStorage.getItem('token')) {
      const Token = localStorage.getItem('token');
      config.headers.Authorization = `Bearer ${Token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use((response: AxiosResponse<any, any>) => {
  if (response.status === 200) {
    const { authorization }= response.headers
    authorization && localStorage.setItem("token", authorization)
    return response.data;
  }
}, (error) => {
    ElMessage.error(ErrorCode(error.response.status))
    return Promise.reject(error)
  }
  )

export default service;